package com.atrix.CinemaView.utils;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import com.atrix.CinemaView.pojo.dto.FileStreamData;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class FileUtil {
    private static final String[] photoSuffixes = new String[]{
            ".jpg", ".png", ".gif", ".jpeg"
    };
    
    private static final String[] videoSuffixes = new String[]{
            ".mp4", ".mkv"
    };
    
    private static final String[] mdSuffixes = new String[]{
            ".md"
    };
    
    public static boolean isVideo(File file) {
        return checkFile(file, videoSuffixes);
    }
    
    public static boolean isPhoto(File file) {
        return checkFile(file, photoSuffixes);
    }
    
    public static boolean isMd(File file) {
        return checkFile(file, mdSuffixes);
    }
    
    private static boolean checkFile(File file, String[] photoSuffixes) {
        if (!file.isFile()) {
            return false;
        }
        String name = file.getName();
        String suffix = getSuffix(name);
        if (suffix == null) {
            return false;
        }
        for (String photoSuffix : photoSuffixes) {
            if (suffix.equals(photoSuffix)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 获取图片类型
     *
     * @param name 图片文件名称
     * @return 类型
     */
    public static String getType(String name) {
        name = getSuffix(name);
        if (name == null) {
            return null;
        }
        return name.substring(1);
    }
    
    /**
     * 获取图片扩展名
     *
     * @param name 图片文件名称
     * @return 扩展名
     */
    public static String getSuffix(String name) {
        int beginIndex = name.lastIndexOf('.');
        if (beginIndex == -1) {
            return null;
        }
        return name.substring(beginIndex).toLowerCase();
    }
    
    /**
     * 向前端输出文件
     *
     * @param file     数据文件
     * @param response http响应
     */
    public static void outputFile(FileStreamData file, HttpServletResponse response) {
        outputFile(file, response, 0);
    }
    
    
    public static void outputFile(FileStreamData file, HttpServletResponse response, long skip) {
        try (
                ServletOutputStream outputStream = response.getOutputStream();
                InputStream inputStream = file.getInputStream()
        ) {
            inputStream.skip(skip);
            IoUtil.copy(inputStream, outputStream);
        } catch (IOException | IORuntimeException ignored) {
        
        }
    }
}
